package com.weita.lightfood.config;

import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * description:
 *
 * @author IT_Monster on 2019/8/4
 */
@Configuration
public class RedisConfig {
    /**
     * 设置过期时间
     */
    private Duration timeToLive = Duration.ofDays(1);
    private RedisSerializer<String> keySerializer = new StringRedisSerializer();
    private RedisSerializer<Object> valueSerializer = new GenericJackson2JsonRedisSerializer();

    /**
     * 配置cacheManager
     * @param redisConnectionFactory    redis连接工厂
     * @return      返回缓存管理器
     */
    @Bean
    public CacheManager myCacheManager(RedisConnectionFactory redisConnectionFactory){
        //配置设置
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(timeToLive)
                .disableCachingNullValues()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer));
        //构建cacheManager
        RedisCacheManager redisCacheManager = RedisCacheManager.builder(redisConnectionFactory)
                .transactionAware()
                .cacheDefaults(config)
                .build();
        return redisCacheManager;
    }

    /**
     * 配置redisTemplate
     * @param redisConnectionFactory    redis连接工厂
     * @return      返回redis操作模板
     */
    @Bean("redisTemplate")
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setHashKeySerializer(keySerializer);
        redisTemplate.setValueSerializer(valueSerializer);
        redisTemplate.setHashValueSerializer(valueSerializer);

        return redisTemplate;

    }
}
